package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.commons.huanxin.utils.HuanXinUtils;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.RecommendUserQueryParam;
import com.tanhua.domain.vo.TodayBest;
import com.tanhua.dubbo.server.api.QuestionApi;
import com.tanhua.dubbo.server.api.UserInfoApi;
import com.tanhua.dubbo.server.api.mongo.RecommendUserApi;
import com.tanhua.server.interceptor.UserThreadLocal;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class TodayBestService {

    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinUtils utils;

    public ResponseEntity queryTodayBest(Long userId) {

        RecommendUser user = this.recommendUserApi.queryTodayBest(userId);

        if (user == null) {
            //未找到最高得分的推荐用户，给出一个默认推荐用户
            user = new RecommendUser();
            user.setUserId(2l);
            user.setScore(95d);
        }

        TodayBest best = new TodayBest();
        // 补全用户信息
        UserInfo userInfo = this.userInfoApi.findByUserId(user.getUserId());

        BeanUtils.copyProperties(userInfo, best);

        best.setId(user.getUserId());

        best.setFateValue(user.getScore().longValue());

        best.setTags(StringUtils.split(userInfo.getTags(), ','));

        return ResponseEntity.ok(best);
    }



    public ResponseEntity queryRecommendUserList(RecommendUserQueryParam queryParam) {

        //根据token查询当前登录的用户信息
        User user = UserThreadLocal.get();

        PageResult result = this.recommendUserApi.queryRecommendUserList(user.getId(), queryParam.getPage(), queryParam.getPagesize());

        List<RecommendUser> records = (List<RecommendUser>) result.getItems();

        // 如果未查询到，需要使用默认推荐列表
        if (CollectionUtils.isEmpty(records)) {
            result = new PageResult(queryParam.getPage(),queryParam.getPagesize(),10,null);
            records = defaultRecommend();
        }

        List<TodayBest> todayBests = new ArrayList<>();

        for (RecommendUser record : records) {

            TodayBest best = new TodayBest();
            // 补全用户信息
            UserInfo userInfo = this.userInfoApi.findByUserId(record.getUserId());

            BeanUtils.copyProperties(userInfo, best);

            best.setId(record.getUserId());

            best.setFateValue(record.getScore().longValue());

            best.setTags(StringUtils.split(userInfo.getTags(), ','));

            todayBests.add(best);
        }

        //对结果集做排序，按照缘分值倒序排序
        Collections.sort(todayBests, (o1, o2) -> Long.valueOf(o2.getFateValue() - o1.getFateValue()).intValue());

        result.setItems(todayBests);

        return ResponseEntity.ok(result);
    }

    private List<RecommendUser> defaultRecommend() {
        String ids = "1,2,3,4,5,6,7,8,9,10";
        List<RecommendUser> records = new ArrayList<>();
        String[] idAttr = StringUtils.split(ids, ',');
        for (String id : idAttr) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(Long.valueOf(id));
            recommendUser.setToUserId(UserThreadLocal.getUserId());
            recommendUser.setScore(RandomUtils.nextDouble(70, 98));
            records.add(recommendUser);
        }
        return records;
    }


//    @Autowired
//    private UserInfoService userInfoService;
//
//    @Autowired
//    private RecommendUserService recommendUserService;
//
//    @Value("${tanhua.default.user}")
//    private Long defaultUserId;
//
//    @Value("${tanhua.default.recommend.users}")
//    private String defaultRecommendUsers;
//
//    @Autowired
//    private QuestionService questionService;
//
//    private static final ObjectMapper MAPPER = new ObjectMapper();
//
//    @Autowired
//    private RestTemplate restTemplate;
//
//    @Autowired
//    private MongoTemplate mongoTemplate;
//
//    @Autowired
//    private IMService imService;
//
//    @Autowired
//    private HuanXinUtils huanXinUtils;
//
//    private List<RecommendUser> defaultRecommend() {
//        List<RecommendUser> records = new ArrayList<>();
//        String[] ss = StringUtils.split(defaultRecommendUsers, ',');
//        for (String s : ss) {
//            RecommendUser recommendUser = new RecommendUser();
//            recommendUser.setUserId(Long.valueOf(s));
//            recommendUser.setToUserId(UserThreadLocal.getUserId());
//            recommendUser.setScore(RandomUtils.nextDouble(70, 98));
//            records.add(recommendUser);
//        }
//        return records;
//    }
//
//
//    public PageResult queryRecommendUserList(RecommendUserQueryParam queryParam) {
//        //根据token查询当前登录的用户信息
//        User user = UserThreadLocal.get();
//        List<RecommendUser> records = this.recommendUserService.queryRecommendUserList(user.getId(), queryParam.getPage(), queryParam.getPagesize());
//
//        // 如果未查询到，需要使用默认推荐列表
//        if (CollectionUtils.isEmpty(records)) {
//            records = defaultRecommend();
//        }
//
//        List<Long> userIds = new ArrayList<>();
//        for (RecommendUser record : records) {
//            userIds.add(record.getUserId());
//        }
//
//
//        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.in("id", userIds); //用户id
//
//        if (queryParam.getAge() != null) {
//            //queryWrapper.lt("age", queryParam.getAge()); //年龄
//        }
//
//        if (StringUtils.isNotEmpty(queryParam.getCity())) {
//            //queryWrapper.eq("city", queryParam.getCity()); //城市
//        }
//
//        //需要查询用户的信息，并且按照条件查询
//        List<UserInfo> userInfos = this.userInfoService.findAll(queryWrapper);
//
//        List<TodayBest> todayBests = new ArrayList<>();
//
//        for (UserInfo userInfo : userInfos) {
//            TodayBest todayBest = new TodayBest();
//            BeanUtils.copyProperties(userInfo, todayBest);
//            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
//            for (RecommendUser record : records) {
//                if (record.getUserId().longValue() == todayBest.getId().longValue()) {
//                    double score = Math.floor(record.getScore());
//                    todayBest.setFateValue(Double.valueOf(score).longValue()); //缘分值
//                }
//            }
//            todayBests.add(todayBest);
//        }
//
//        //对结果集做排序，按照缘分值倒序排序
//        Collections.sort(todayBests, (o1, o2) -> Long.valueOf(o2.getFateValue() - o1.getFateValue()).intValue());
//
//        return new PageResult(0, queryParam.getPagesize(), 0, queryParam.getPage(), todayBests);
//    }
//
//    public TodayBest queryTodayBest(Long userId) {
//
//        User user = UserThreadLocal.get();
//
//        TodayBest todayBest = new TodayBest();
//        //补全信息
//        UserInfo userInfo = this.userInfoService.findById(userId);
//        BeanUtils.copyProperties(userInfo, todayBest);
//        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
//
//        double score = this.recommendUserService.queryScore(userId, user.getId());
//
//        if (score == 0) {
//            score = 98; //默认分值
//        }
//
//        todayBest.setFateValue(Double.valueOf(score).longValue());
//        return todayBest;
//    }
//
//
//
//    public List<NearUserVo> queryNearUser(String gender, String range) {
//        User user = UserThreadLocal.get();
//        //查询当前用户的地理位置
//        Query query1 = Query.query(Criteria.where("userId").is(user.getId()));
//        UserLocation userLocation = this.mongoTemplate.findOne(query1, UserLocation.class);
//
//        Double longitude = userLocation.getLongitude();
//        Double latitude = userLocation.getLatitude();
//
//        //查询附近的好友
//        // 根据传入的坐标，进行确定中心点
//        GeoJsonPoint geoJsonPoint = new GeoJsonPoint(longitude, latitude);
//        // 画圈的半径
//        Distance distance = new Distance(Integer.valueOf(range) / 1000, Metrics.KILOMETERS);
//        // 画了一个圆圈
//        Circle circle = new Circle(geoJsonPoint, distance);
//
//        Query query2 = Query.query(Criteria.where("location").withinSphere(circle));
//
//        List<UserLocation> userLocations = this.mongoTemplate.find(query2, UserLocation.class);
//
//        List<NearUserVo> result = new ArrayList<>();
//
//        for (UserLocation location : userLocations) {
//            UserInfo info = userInfoService.findById(location.getUserId());
//            if(info.getGender().equalsIgnoreCase(gender)) {
//                NearUserVo vo = new NearUserVo();
//                BeanUtils.copyProperties(info, vo);
//                result.add(vo);
//            }
//        }
//
//        return result;
//    }
//
//
//
//
//    public List<TodayBest> queryCardsList() {
//
//        User user = UserThreadLocal.get();
//
//        List<RecommendUser> records = recommendUserService.queryRecommendUserList(user.getId(), 1, 50);
//
//        if (CollectionUtils.isEmpty(records)) {
//            records = defaultRecommend();
//        }
//
//        List<RecommendUser> newRecommendUserList = new ArrayList<>();
//
//        int showCount = Math.min(10, records.size());
//
//        for (int i = 0; i < showCount; i++) {
//            createRecommendUser(newRecommendUserList, records);
//        }
//
//        List<Long> userIds = new ArrayList<>();
//
//        for (RecommendUser recommendUser : newRecommendUserList) {
//            userIds.add(recommendUser.getUserId());
//        }
//
//
//
//        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.in("user_id", userIds);
//
//
//        List<UserInfo> userInfoList = this.userInfoService.findAll(queryWrapper);
//
//        List<TodayBest> result = new ArrayList<>();
//
//        for (UserInfo userInfo : userInfoList) {
//            TodayBest todayBest = new TodayBest();
//            BeanUtils.copyProperties(userInfo, todayBest);
//            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
//            result.add(todayBest);
//        }
//
//        return result;
//    }
//
//
//
//
//    /**
//     * 递归随机生成推荐好友，保证不重复
//     */
//    private void createRecommendUser(List<RecommendUser> newRecommendUserList,
//                                     List<RecommendUser> records){
//        RecommendUser recommendUser = records.get(RandomUtils.nextInt(0, records.size() - 1));
//        if(!newRecommendUserList.contains(recommendUser)){
//            newRecommendUserList.add(recommendUser);
//        }else{
//            // 开始递归
//            createRecommendUser(newRecommendUserList, records);
//        }
//    }
//
//    public void likeUser(Long likeUserId) {
//
//        Long userId = UserThreadLocal.getUserId();
//
//        Query query = Query.query(Criteria.where("userId").is(userId)
//                .and("likeUserId").is(likeUserId));
//
//        if (!mongoTemplate.exists(query, UserLike.class)) {
//            UserLike userLike = new UserLike();
//            userLike.setId(ObjectId.get());
//            userLike.setLikeUserId(likeUserId);
//            userLike.setUserId(userId);
//            userLike.setCreated(System.currentTimeMillis());
//            this.mongoTemplate.save(userLike);
//        }
//
//        query = Query.query(Criteria.where("userId").is(likeUserId)
//                .and("likeUserId").is(userId));
//
//        if (mongoTemplate.exists(query, UserLike.class)) {
//            //相互喜欢成为好友
//            this.imService.contactUser(likeUserId);
//        }
//    }
//
//    public void disLikeUser(Long likeUserId) {
//        Query query = Query.query(Criteria.where("userId").is(UserThreadLocal.getUserId())
//                .and("likeUserId").is(likeUserId));
//        DeleteResult deleteResult = mongoTemplate.remove(query, UserLike.class);
//    }
//
//
//    /**
//     * 回复陌生人问题，发送消息给对方
//     */
//    public void replyQuestion(Long userId, String reply) {
//
//        User user = UserThreadLocal.get();
//        UserInfo userInfo = this.userInfoService.findById(user.getId());
//
//        //构建消息内容
//        Map<String, Object> map = new HashMap<>();
//        map.put("userId", user.getId().toString());
//        map.put("nickname", this.queryQuestion(userId));
//        map.put("strangerQuestion", userInfo.getNickname());
//        map.put("reply", reply);
//
//        String msg = JSON.toJSONString(map);
//
//        huanXinUtils.sendMsg(userId.toString(),msg);
//    }
//
//    public TodayBest queryTodayBest() {
//
//        //根据token查询当前登录的用户信息
//        User user = UserThreadLocal.get();
//
//        TodayBest todayBest = this.recommendUserService.queryTodayBest(user.getId());
//
//        if (todayBest == null) {
//            //未找到最高得分的推荐用户，给出一个默认推荐用户
//            todayBest = new TodayBest();
//            todayBest.setId(defaultUserId);
//            todayBest.setFateValue(95L);
//        }
//
//        // 补全用户信息
//        UserInfo userInfo = this.userInfoService.findById(todayBest.getId());
//
//        if (null != userInfo) {
//            todayBest.setAge(userInfo.getAge());
//            todayBest.setAvatar(userInfo.getAvatar());
//            todayBest.setGender(userInfo.getGender());
//            todayBest.setNickname(userInfo.getNickname());
//            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
//        }
//
//        return todayBest;
//    }
//
//
    public ResponseEntity queryQuestion(Long userId) {
        Question question = this.questionApi.queryQuestion(userId);
        return ResponseEntity.ok(question==null?"":question.getTxt());
    }

    /**
     * 回复陌生人问题，发送消息给对方
     */
    public ResponseEntity replyQuestion(Long userId, String reply) {

        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoApi.findByUserId(user.getId());
        Question question = this.questionApi.queryQuestion(userId);

        //构建消息内容
        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getId().toString());
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", question.getTxt());
        map.put("reply", reply);

        String msg = JSON.toJSONString(map);

        utils.sendMsg(userId.toString(),msg);

        return ResponseEntity.ok(null);
    }
}
